package com.project;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.regex.*;

public class DB_Order extends DB_Operator {

    /**
     * Default constructor
     */
    public DB_Order() {
    }

    // 获取当前时间的方法
    private String getCurrentTime() {
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return now.format(formatter);
    }

    // 实现添加方法
    /**
     * @param input 输入
     * @return 返回
     */
    public boolean add(List<String> input) {
        if (input.size() != 3) { // 1 个 uid, 1 个 aid, 1 个 payamount
            return false;
        }
        connect();
        String sql = "INSERT INTO `Order` (`uid`, `aid`, `time`, `payamount`, `state`) VALUES (?,?,?,?,?)";
        try (PreparedStatement PStmt = con.prepareStatement(sql)) {
            PStmt.setInt(1, Integer.parseInt(input.getFirst()));
            PStmt.setInt(2, Integer.parseInt(input.get(1)));
            PStmt.setString(3, getCurrentTime());
            PStmt.setString(4, input.get(2));
            PStmt.setInt(5, 0); // 默认未支付
            int rowsAffected = PStmt.executeUpdate();
            close();
            return rowsAffected > 0;
        } catch (SQLException e) {
            System.err.println("出现异常：" + e.getMessage());
            return false;
        }
    }

    /**
     * @param input 输入
     * @return 返回
     */
    public boolean delete(List<String> input) {
        if (input.isEmpty()) {
            return false;
        }
        connect();
        String deleteSql = "DELETE FROM `Order` WHERE `oid` =?";
        String maxIdSql = "SELECT MAX(oid) FROM `Order`";
        String updateAutoIncrementSql = "ALTER TABLE `Order` AUTO_INCREMENT =?";
        try (PreparedStatement deletePStmt = con.prepareStatement(deleteSql);
             PreparedStatement maxIdPStmt = con.prepareStatement(maxIdSql);
             PreparedStatement updatePStmt = con.prepareStatement(updateAutoIncrementSql)) {
            deletePStmt.setInt(1, Integer.parseInt(input.getFirst()));
            int rowsAffected = deletePStmt.executeUpdate();

            ResultSet rs = maxIdPStmt.executeQuery();
            int maxId = 1;
            if (rs.next()) {
                maxId = rs.getInt(1) + 1;
            }
            updatePStmt.setInt(1, maxId);
            updatePStmt.executeUpdate();

            close();
            return rowsAffected > 0;
        } catch (SQLException e) {
            System.err.println("出现异常：" + e.getMessage());
            close();
            return false;
        }
    }

    /**
     * @param input 输入
     * @return 返回
     */
    public List<String> find(List<String> input) {
        List<String> result = new ArrayList<>();
        if (input == null || input.isEmpty()) return result;

        connect();
        StringBuilder sql = new StringBuilder("SELECT oid, uid, aid, time, payamount, state FROM `Order` WHERE 1=1");
        List<String> params = new ArrayList<>();

        try {
            for (String condition : input) {
                Pattern pattern = Pattern.compile("(<=|>=|=|<|>)");
                Matcher matcher = pattern.matcher(condition);
                if (matcher.find()) {
                    String operator = matcher.group();
                    String[] parts = condition.split(Pattern.quote(operator), 2);
                    String field = parts[0].trim().toLowerCase();
                    String value = parts[1].trim();

                    if (!Set.of("oid", "uid", "aid", "time", "payamount", "state", "orderby").contains(field)) {
                        continue;
                    }

                    if (field.equals("state")) {
                        try {
                            Integer.parseInt(value);
                        } catch (NumberFormatException e) {
                            continue;
                        }
                    }

                    if (field.equals("orderby")) {
                        sql.append(" ?");
                    } else {
                        sql.append(" AND ").append(field).append(operator).append("?");
                    }
                    params.add(value);
                }
            }

            try (PreparedStatement PStmt = con.prepareStatement(sql.toString())) {
                for (int i = 0; i < params.size(); i++) {
                    String field = input.get(i).split(Pattern.quote(params.get(i)))[0].trim().toLowerCase();

                    if (field.equals("state") || field.equals("payamount")) {
                        PStmt.setInt(i + 1, Integer.parseInt(params.get(i)));
                    } else {
                        PStmt.setString(i + 1, params.get(i));
                    }
                }

                ResultSet rs = PStmt.executeQuery();

                while (rs.next()) {
                    String row = String.join(",",
                            rs.getString("oid"),
                            rs.getString("uid"),
                            rs.getString("aid"),
                            rs.getString("time"),
                            rs.getString("payamount"),
                            rs.getString("state")
                    );
                    result.add(row);
                }
            }
        } catch (SQLException | NumberFormatException e) {
            System.err.println("出现异常：" + e.getMessage());
        } finally {
            close();
        }
        return result;
    }

    /**
     * @param conditionColumn 条件
     * @param conditionValue 值
     * @param returnList 返回
     */
    public void find(String conditionColumn, String conditionValue, List<String> returnList) {
        connect();
        String sql = "SELECT * FROM `Order` WHERE true";
        if (!conditionColumn.isEmpty() &&!conditionValue.isEmpty()) {
            sql += " AND `" + conditionColumn + "` =?";
        }
        try (PreparedStatement PStmt = con.prepareStatement(sql)) {
            if (!conditionColumn.isEmpty() &&!conditionValue.isEmpty()) {
                PStmt.setString(1, conditionValue);
            }
            ResultSet rs = PStmt.executeQuery();
            while (rs.next()) {
                returnList.add(rs.getString("oid"));
                returnList.add(rs.getString("uid"));
                returnList.add(rs.getString("aid"));
                returnList.add(rs.getString("time"));
                returnList.add(rs.getString("payamount"));
                returnList.add(rs.getString("state"));
            }
            close();
        } catch (SQLException e) {
            System.err.println("出现异常：" + e.getMessage());
            close();
        }
    }

    // 实现更新方法
    /**
     * @param input 输入
     * @return 返回
     */
    public boolean update(List<String> input) {
        if (input.size() != 5) {
            return false;
        }
        connect();
        String sql = "UPDATE `Order` SET `uid` =?, `aid` =?, `payamount` =?, `state` =? WHERE `oid` =?";
        try (PreparedStatement PStmt = con.prepareStatement(sql)) {
            PStmt.setInt(1, Integer.parseInt(input.get(1)));
            PStmt.setInt(2, Integer.parseInt(input.get(2)));
            PStmt.setInt(3, Integer.parseInt(input.get(3)));
            PStmt.setInt(4, Integer.parseInt(input.get(4)));
            PStmt.setInt(5, Integer.parseInt(input.get(0)));
            int rowsAffected = PStmt.executeUpdate();
            close();
            return rowsAffected > 0;
        } catch (SQLException e) {
            System.err.println("出现异常：" + e.getMessage());
            close();
            return false;
        }
    }
}